/*! AdminLTE app.js
 * ================
 * Main JS application file for AdminLTE v2. This file
 * should be included in all pages. It controls some layout
 * options and implements exclusive AdminLTE plugins.
 *
 * @Author  Almsaeed Studio
 * @Support <http://www.almsaeedstudio.com>
 * @Email   <abdullah@almsaeedstudio.com>
 * @version 2.3.8
 * @license MIT <http://opensource.org/licenses/MIT>
 */

//Make sure jQuery has been loaded before app.js
if (typeof jQuery === "undefined") {
    throw new Error("AdminLTE requires jQuery");
}

/* AdminLTE
 *
 * @type Object
 * @description $.AdminLTE is the main object for the template's app.
 *              It's used for implementing functions and options related
 *              to the template. Keeping everything wrapped in an object
 *              prevents conflict with other plugins and is a better
 *              way to organize our code.
 */
$.AdminLTE = {};

/* --------------------
 * - AdminLTE Options -
 * --------------------
 * Modify these options to suit your implementation
 */
$.AdminLTE.options = {
    //General animation speed for JS animated elements such as box collapse/expand and
    //sidebar treeview slide up/down. This options accepts an integer as milliseconds,
    //'fast', 'normal', or 'slow'
    animationSpeed: 500,
    //Sidebar push menu toggle button selector
    sidebarToggleSelector: "[data-toggle='offcanvas']",
    //Activate sidebar push menu
    sidebarPushMenu: true,

    //Control Sidebar Tree views
    enableControlTreeView: true,

    //The standard screen sizes that bootstrap uses.
    //If you change these in the variables.less file, change
    //them here too.
    screenSizes: {
        xs: 480,
        sm: 768,
        md: 992,
        lg: 1200
    }
};

$.AdminLTE.checkSessionTimeout = function (redirectUrl) {
    //检查当前用户会话是否已过期
    $.get("/checkSessionTimeout", function (response) {
        if (response && response == "ok") {
            //菜单单击事件,导航标题及主iframe内容动态切换
            if (redirectUrl)
                $("#main").attr("src", redirectUrl);
        } else {
            window.location.href = '/login';
        }
    });
};

/* ------------------
 * - Implementation -
 * ------------------
 * The next block of code implements AdminLTE's
 * functions and plugins as specified by the
 * options above.
 */
$(function () {
    "use strict";

    //Fix for IE page transitions
    $("body").removeClass("hold-transition");

    //Extend options if external options exist
    if (typeof AdminLTEOptions !== "undefined") {
        $.extend(true,
            $.AdminLTE.options,
            AdminLTEOptions);
    }

    //Easy access to options
    var o = $.AdminLTE.options;

    //Set up the object
    _init();

    //Activate the layout maker
    $.AdminLTE.layout.activate();

    //Enable sidebar tree view controls
    if (o.enableControlTreeView) {
        $.AdminLTE.tree('.sidebar');
    }

    //Activate sidebar push menu
    if (o.sidebarPushMenu) {
        $.AdminLTE.pushMenu.activate(o.sidebarToggleSelector);
    }

    //默认展开第一个菜单
    if (!$('.sidebar-menu li').hasClass('active')) {
        $('.sidebar-menu li:first').addClass('active');
    }

    //头部链接检查会话超时及面包屑功能
    $('.navbar-custom-menu a').click(function (e) {
        var href = $(this).attr("href");
        if (href === '/' || href === '#'|| href === '/logout')
            return;

        $('#navItem').hide();
        $('#navItem').text('');
        $("#navUrl").text($(this).text());
        $("#navUrl").attr("href", href);

        $.AdminLTE.checkSessionTimeout($(this).attr("href"));
        e.preventDefault();
    });

    //面包屑导航栏接检查会话超时
    $('#navUrl').click(function (e) {
        $.AdminLTE.checkSessionTimeout($('#navUrl').attr("href"));

        $('#navItem').hide();
        $('#navItem').text('');

        e.preventDefault();
    });

    $('#main').load(function () {
        var mainContents = $('#main').contents();

        // 动态面包屑
        var navItems = mainContents.find('.navItem');
        if (navItems.length > 0) {
            var title = mainContents.attr("title");
            $('#navItem').text(title);
            $("#navItem").css('display', 'inline');
        } else {
            $('#navItem').hide();
            $('#navItem').text('');
        }

        // iframe页面的按钮检查会话超时
        mainContents.find('button,a').click(function () {
            $.AdminLTE.checkSessionTimeout();
        });
    });
});

/* ----------------------------------
 * - Initialize the AdminLTE Object -
 * ----------------------------------
 * All AdminLTE functions are implemented below.
 */
function _init() {
    'use strict';
    /* Layout
     * ======
     * Fixes the layout height in case min-height fails.
     *
     * @type Object
     * @usage $.AdminLTE.layout.activate()
     *        $.AdminLTE.layout.fix()
     *        $.AdminLTE.layout.fixSidebar()
     */
    $.AdminLTE.layout = {
        activate: function () {
            var _this = this;
            _this.fix();
            $('body, html, .wrapper').css('height', 'auto');
            $(window, ".wrapper").resize(function () {
                _this.fix();
            });
        },
        fix: function () {
            //Get window height and the wrapper height
            var window_height = $(window).height();
            var footer_height = $('.main-footer').outerHeight() || 0;
            var main_header_height = $('.sidebar-toggle').outerHeight() || 0;
            var content_header_height = $(".content-header").height() || 0;

            $(".main-sidebar").height(window_height - main_header_height);

            var $content = $('.content');
            $content.height(window_height - main_header_height - footer_height - content_header_height);
            $("#main").height($content.height());

            // 菜单树增加滚动条
            $('.sidebar').slimscroll({
                height: $(".main-sidebar").height(),
                opacity: 0
            });
        }
    };

    /* PushMenu()
     * ==========
     * Adds the push menu functionality to the sidebar.
     *
     * @type Function
     * @usage: $.AdminLTE.pushMenu("[data-toggle='offcanvas']")
     */
    $.AdminLTE.pushMenu = {
        activate: function (toggleBtn) {
            //Get the screen sizes
            var screenSizes = $.AdminLTE.options.screenSizes;

            //Enable sidebar toggle
            $(document).on('click', toggleBtn, function (e) {
                e.preventDefault();

                // 菜单列表增加滚动条
                if ($("body").hasClass('sidebar-collapse')) {
                    $('.sidebar').slimscroll({
                        height: $(".main-sidebar").height(),
                        opacity: 0
                    });
                } else {
                    $('.sidebar').slimscroll({
                        destroy: true
                    });

                    $('.sidebar').removeAttr('style');
                }

                //Enable sidebar push menu
                if ($(window).width() > (screenSizes.sm - 1)) {
                    if ($("body").hasClass('sidebar-collapse')) {
                        $("body").removeClass('sidebar-collapse').trigger('expanded.pushMenu');
                    } else {
                        $("body").addClass('sidebar-collapse').trigger('collapsed.pushMenu');
                    }
                }
                //Handle sidebar push menu for small screens
                else {
                    if ($("body").hasClass('sidebar-open')) {
                        $("body").removeClass('sidebar-open').removeClass('sidebar-collapse').trigger('collapsed.pushMenu');
                    } else {
                        $("body").addClass('sidebar-open').trigger('expanded.pushMenu');
                    }
                }
            });

            $(".content-wrapper").click(function () {
                //Enable hide menu when clicking on the content-wrapper on small screens
                if ($(window).width() <= (screenSizes.sm - 1) && $("body").hasClass("sidebar-open")) {
                    $("body").removeClass('sidebar-open');
                }
            });
        },
        expand: function () {
            $("body").removeClass('sidebar-collapse').addClass('sidebar-expanded-on-hover');
        },
        collapse: function () {
            if ($('body').hasClass('sidebar-expanded-on-hover')) {
                $('body').removeClass('sidebar-expanded-on-hover').addClass('sidebar-collapse');
            }
        }
    };

    /* Tree()
     * ======
     * Converts the sidebar into a multilevel
     * tree view menu.
     *
     * @type Function
     * @Usage: $.AdminLTE.tree('.sidebar')
     */
    $.AdminLTE.tree = function (menu) {
        var _this = this;
        var animationSpeed = $.AdminLTE.options.animationSpeed;
        $(document).off('click', menu + ' li a')
            .on('click', menu + ' li a', function (e) {
                //Get the clicked link and the next element
                var $this = $(this);
                var checkElement = $this.next();

                //Check if the next element is a menu and is visible
                if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible')) && (!$('body').hasClass('sidebar-collapse'))) {
                    //Close the menu
                    checkElement.slideUp(animationSpeed, function () {
                        checkElement.removeClass('menu-open');
                        //Fix the layout in case the sidebar stretches over the height of the window
                        //_this.layout.fix();
                    });
                    checkElement.parent("li").removeClass("active");
                }
                //If the menu is not visible
                else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {
                    //Get the parent menu
                    var parent = $this.parents('ul').first();
                    //Close all open menus within the parent
                    var ul = parent.find('ul:visible').slideUp(animationSpeed);
                    //Remove the menu-open class from the parent
                    ul.removeClass('menu-open');
                    //Get the parent li
                    var parent_li = $this.parent("li");

                    //Open the target menu and add the menu-open class
                    checkElement.slideDown(animationSpeed, function () {
                        //Add the class active to the parent li
                        checkElement.addClass('menu-open');
                        parent.find('li.active').removeClass('active');
                        parent_li.addClass('active');
                        //Fix the layout in case the sidebar stretches over the height of the window
                        _this.layout.fix();
                    });
                }
                //if this isn't a link, prevent the page from being redirected
                if (checkElement.is('.treeview-menu')) {
                    e.preventDefault();
                }

                if ($this.is('.treeview-menu li a')) {
                    $("#navUrl").text($this.text());
                    $("#navUrl").attr("href", $this.attr("href"));
                    $('#navItem').hide();
                    $('#navItem').text('');

                    //检查当前用户会话是否已过期
                    $.AdminLTE.checkSessionTimeout($this.attr("href"));

                    e.preventDefault();
                }
            });
    };
}